<script setup lang="ts">
defineOptions({
  name: "DieselSupplyTrend"
});
import { ref, watch, getCurrentInstance, onMounted, nextTick, reactive, toRefs, computed, onUnmounted } from "vue";
import yearPicker from "@/views/common/energy/components/yearPickerSmall.vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { PxMessage } from "px-ui";
import barCom from "./barCom/index.vue";
import { queryScadaIndicator } from "@/api/machineApi";

interface Props {
  /**  有 title 时传入 */
  title?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  /**  是否暗色，默认为false */
  dark?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: "供给趋势-柴油",
  dark: false,
  width: 330,
  height: 200,
  boxShadow: false,
  borderRidus: false
});

interface queryForm {
  queryTimeGranularity?: string;
  level?: string;
  startTime?: string;
  endTime?: string;
}

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

interface Emits {
  /**  title 右侧按钮点击后触发 */
  (event: "btn-click"): void;
}

const emits = defineEmits<Emits>();

const echartsKey = ref<string>(Math.random().toString(36).slice(2, 10));

const title_height = computed(() => (props.title ? "38px" : "0px"));
const min_width = computed(() => `${props.width}px`);
const min_height = computed(() => `${props.height}px`);

const energyType = ref("all");

const tablePieKey = ref(Date.now());

const { proxy }: any = getCurrentInstance();

// 定义数据
const dateRange = ref<any>([]);

const yearStart = ref("");
const yearEnd = ref("");
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref<any>({ startYear: new Date().getFullYear(), endYear: new Date().getFullYear() });
// const dateValue = ref<any>({});
// 选完/输入完成的回调
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00`;
  yearEnd.value = `${endYear}-12-31 23:59:59`;
};

const pageData = ref<any>({});

const costOptions = ref<UtilsEChartsOption>({});

const dataList = ref<any>([]);

// 合并同类项数组
const mergeDataByProperty = (arr, type) => {
  const merged = [];
  let propertyValues = {};
  const keyArr: any = Array.from(new Set(arr.map(item => item.point))) || [];
  for (const val in keyArr) {
    propertyValues[keyArr[val]] = [];
    console.log(val);
    arr.forEach(item => {
      if (item.point === keyArr[val]) {
        propertyValues[keyArr[val]].push({
          name: item[type],
          value: Number(item.sum_value)
        });
      }
    });
  }
  return propertyValues;
};

const clickHandler = () => emits("btn-click");

const getXiasDataName = name => {
  let str = name || "";
  if (queryParams.value.queryTimeGranularity === "Daily") {
    return str.substring(0, 10);
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    return str.substring(0, 7);
  } else {
    return str.substring(0, 4);
  }
};

const getPageData = async () => {
  // 通用组件在此处替换指标点位["1", "2", "3"]
  const list = ["2_B1_OIL4_LIT1_I_AI_HMI_CALCLUATE"];
  let type = "";
  switch (queryParams.value.queryTimeGranularity) {
    case "Daily":
      type = "day";
      break;
    case "Monthly":
      type = "month";
      break;
    case "Yearly":
      type = "year";
      break;

    default:
      break;
  }
  const res: any = await queryScadaIndicator({
    contentType: "LIST",
    bucketWidth: 1,
    bucketUnit: type,
    point: [...list],
    scale: 0.2,
    indicators: ["SUM"],
    startTime: queryParams.value.startTime,
    endTime: queryParams.value.endTime
  });
  const mergeData: any = mergeDataByProperty(res.rows, type) || {};
  const xData: any =
    Object.keys(mergeData) && Object.keys(mergeData).length ? mergeData[Object.keys(mergeData)[0]].map(e => getXiasDataName(e.name)) : [];
  const seriesData = Object.keys(mergeData).map((item, index) => {
    return {
      name: "柴油供给量",
      type: "bar",
      emphasis: {
        focus: "series",
        blurScope: "coordinateSystem"
      },
      data: mergeData[item]
    };
  });
  const legendData: any = seriesData.map(e => e.name) || [];
  costOptions.value = labelLayoutFn(xData, legendData, seriesData);
  // tablePieKey.value = Date.now();
};

const labelLayoutFn = (xData: any, legendData: any, seriesData: any) => {
  const options: UtilsEChartsOption = {
    color: ["#3B82F6"],
    tooltip: {
      trigger: "axis",
      confine: true,
      formatter: function (params) {
        if (params instanceof Array) {
          let str = "";
          str += `${params[0].axisValue}<br/>`;
          params.forEach((m, index) => {
            str += `<span class="chart-tooltip-color" style="display: inline-block;margin-right: 10px;background-color: ${m.color}; width: 10px;height: 10px;border-radius: 100%;margin-right: 5px"></span>`;
            str += `${m.seriesName}: ${m.data.value}&nbsp`;
            str += `${index % 3 === 0 ? "<br/>" : ""}`;
          });
          return str;
        }
      },
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "0px",
      top: "40px",
      right: "10px",
      bottom: "10px",
      containLabel: true
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      data: legendData || []
    },
    xAxis: {
      type: "category",
      data: xData || []
    },
    yAxis: {
      type: "value"
    },
    series: seriesData || []
  };
  return options;
};

const queryParams = ref<queryForm>({
  queryTimeGranularity: "Monthly",
  level: ""
});

const queryTypeParams = ref({
  energyType: "Electricity"
});

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const handleChangeFn = (val: string) => {
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  switch (val) {
    case "Daily":
      dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
      // queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
      // queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
      break;
    case "Monthly":
      dateRange.value = [`${year}-${month}`, `${year}-${month}`];
      // queryParams.value.startTime = dateRange.value[0] + "-01 00:00:00";
      // queryParams.value.endTime = dateRange.value[1] + "-31 23:59:59";
      break;
    case "Yearly":
      let yearS = new Date().getFullYear();
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearS}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

// 获取某月最后一天
const getMonthLastDay = (y, m) => {
  let date = new Date(y, m - 1, "01");
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);
  let cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
  return cdate.getDate();
};

const factoryName = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  factoryName.value = queryParams.value.level;
  if (queryParams.value.queryTimeGranularity === "Daily") {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 23:59:59";
    // queryParams.value.startTime =
    //   queryParams.value.startTime.indexOf("00") != -1 ? queryParams.value.startTime : queryParams.value.startTime + " 00:00:00";
    // queryParams.value.endTime = queryParams.value.endTime.indexOf("59") != -1 ? queryParams.value.endTime : queryParams.value.endTime + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    queryParams.value.startTime = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
    const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
    queryParams.value.endTime = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  } else {
    queryParams.value.startTime = yearStart.value;
    queryParams.value.endTime = yearEnd.value;
  }
  console.log(queryParams.value.startTime, queryParams.value.endTime);
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    }
  });
  getPageData();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
}

// 反转数组
const reverseArray = (arr: any[]) => {
  let newArr = [];
  arr.forEach((item: any) => {
    newArr.unshift(item);
  });
  return newArr;
};

const initQuery = () => {
  queryParams.value.queryTimeGranularity = "Monthly";
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  dateRange.value = [`${year}-${month}`, `${year}-${month}`];
  queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
  queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
  queryParams.value.level = "";
  getPageData();
};

onMounted(async () => {
  initQuery();
});
</script>

<template>
  <div class="today-task" :class="{ boxShadow, borderRidus, 'model-title-com-dark': dark }">
    <modelTitle v-if="title" :title="title">
      <div class="model-title-slot">
        <px-button v-if="button" type="primary" size="small" plain @click="clickHandler">{{ button }}</px-button>
        <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
          <px-form-item label="时间维度" prop="dataFormat" style="width: 280px">
            <px-radio-group v-model="queryParams.queryTimeGranularity" style="margin-left: 10px" @change="handleChangeFn">
              <!-- <px-radio size="small" label="Hourly">小时</px-radio> -->
              <px-radio size="small" label="Daily">日</px-radio>
              <px-radio size="small" label="Monthly">月</px-radio>
              <px-radio size="small" label="Yearly">年</px-radio>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="时间范围" style="width: 380px">
            <!-- <px-time-picker
              v-if="queryParams.queryTimeGranularity === 'Hourly'"
              v-model="dateRange"
              is-range
              range-separator="-"
              format="HH"
              value-format="HH"
              start-placeholder="开始小时"
              end-placeholder="结束小时"
            /> -->
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Daily'"
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Monthly'"
              v-model="dateRange"
              type="monthrange"
              value-format="YYYY-MM"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
            />
            <!-- <div v-else-if="queryParams.queryTimeGranularity === 'Yearly'" class="select_year">
              <px-date-picker v-model="queryParams.startTime" value-format="YYYY" type="year" placeholder="开始年份" />
              <span>&nbsp;-&nbsp;</span>
              <px-date-picker v-model="queryParams.endTime" value-format="YYYY" type="year" placeholder="结束年份" />
            </div> -->
            <div v-if="queryParams.queryTimeGranularity === 'Yearly'">
              <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </div>
          </px-form-item>
          <!-- <px-form-item label="厂区">
            <px-select v-model="queryParams.level" clearable placeholder="请选择层级">
              <px-option v-for="item in systemList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item> -->
          <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
          <px-button icon="" @click="resetQuery">重置</px-button>
        </px-form>
      </div>
    </modelTitle>
    <div class="echarts-chart-com">
      <barCom :width="300" :height="200" :options="costOptions" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.today-task {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: #fff;

  .model-title-slot {
    display: flex;
    gap: 16px;
    align-items: center;

    .right-text {
      font-weight: 600;
      line-height: 1;
      color: var(--px-color-primary);
    }

    .px-icon {
      cursor: pointer;
    }
  }

  .echarts-chart-com {
    width: 100%;
    height: calc(100% - v-bind(title_height));
  }
}

.px-form-item {
  margin-bottom: 0;
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.borderRidus {
  border-radius: 4px;
}

.model-title-com-dark {
  color: #fff;
  background: linear-gradient(90deg, #062e51ff, #001e3bff);
  border: 1px solid #83b2ffff;
  box-shadow: inset 0 0 10px 0 #83b2ffff;

  .title-text {
    color: #fff !important;
  }
}
</style>
